//
//  HWNetworkModule.m
//  HWNetworkModule
//
//  Created by yehuawei on 2018/11/21.
//  Copyright © 2018 postop. All rights reserved.
//

#import "HWNetworkModule.h"

@interface HWNetworkModule ()

@property (nonatomic,copy)NetworkResponseHandleBlock commonSuccessBlock;
@property (nonatomic,copy)NetworkResponseHandleBlock commonFailureBlock;

@end

@implementation HWNetworkModule

//全局变量
static id _instance = nil;

//单例方法
+(instancetype)sharedInstance
{
    return [[self alloc] init];
}

////alloc会调用allocWithZone:
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    //只进行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}


#pragma mark - 

-(void)setCommonSucessHandle:(NetworkResponseHandleBlock)handle
{
    self.commonSuccessBlock = handle;
}

-(void)setCommonFailureHandle:(NetworkResponseHandleBlock)handle
{
    self.commonFailureBlock = handle;
}

-(void)startRequest:(YTKRequest *)httpRequest
{
    [httpRequest startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (self.commonSuccessBlock) {
            self.commonSuccessBlock(request);
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (self.commonFailureBlock) {
            self.commonFailureBlock(request);
        }
    }];
}

-(void)startRequest:(YTKRequest *)httpRequest success:(nullable YTKRequestCompletionBlock)success failure:(nullable YTKRequestCompletionBlock)failure
{
    [httpRequest startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (self.commonSuccessBlock) {
            if (self.commonSuccessBlock(request)) {
                success(request);
            }
        } else {
            success(request);
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (self.commonFailureBlock) {
            if (self.commonFailureBlock(request)) {
                failure(request);
            }
        } else {
            failure(request);
        }
        
        
    }];
}

#pragma mark - Setter
-(void)setBaseUrl:(NSString *)baseUrl
{
    _baseUrl = baseUrl;
    [YTKNetworkConfig sharedConfig].baseUrl = _baseUrl;
}

-(void)setCdnUrl:(NSString *)cdnUrl
{
    _cdnUrl = cdnUrl;
    [YTKNetworkConfig sharedConfig].cdnUrl = _cdnUrl;
}

@end
